let Vue = null;
function install(_Vue){
  Vue = _Vue;
  Vue.mixin({
    beforeCreate() {
      if(this.$options.router){
        this.$router = this.$options.router
      }else if (this.$parent){
        this.$router = this.$parent.$router;
      }
    },
  })
  Vue.component('router-link',{
    props:{
      to:{
        require:true
      }
    },
    render(h){
      return h('a',{
        attrs:{
          href:"#"+this.to
        }
      },this.$slots.default)
    }
  })
  Vue.component('router-view',{
    render(h){
      // this   是vue组件
      // this.$router.routerMap[this.$router._route]
      return h(this.$router.routerMap[this.$router._route])
    }
  })
}
class VueRouter{
  constructor(options){
    let {routes}= options;// 路由映射表
    this.routerMap = {};// {'/home':Home,'/list':List}
    routes.forEach(item=>{
      this.routerMap[item.path] = item.component
    })
    window.addEventListener('load',()=>{
      location.hash = location.hash || '/';
      this._route = location.hash.slice(1)
    })
    this._route = location.hash.slice(1)
    Vue.util.defineReactive(this,'_route','/')
    // popState事件        pushState和replaceState
    window.onhashchange = ()=>{
      this._route = location.hash.slice(1);
      // console.log(this._route)
    }
  }
}
VueRouter.install = install;

export default VueRouter